<?php
/**
 * Created by PhpStorm.
 * User: changshuiwang
 * Date: 2016/7/27
 * Time: 10:07
 */

namespace common\models;
use Yii;
use yii\db\ActiveRecord;

class Score extends ActiveRecord
{

    public function rules()
    {
        return [
            // username and password are both required
            [['score','stu_id','type'], 'required', 'on'=> 'add'],
            [['score'], 'number', 'message'=>'分数请输入数字', 'on'=>['add','modify']],
            [['stu_id'], 'validateStu_id', 'on'=>['add']],
            [['stu_id'], 'validateStu_idAlive', 'on'=>['modify']],
            ['type', 'in', 'range' => [1,2,3], 'on'=>['add'], 'message'=>'请选择正确的分类'],
        ];
    }

    /*
     * 验证学生表中有数据，同时成绩表中没有数据
     */
    public function validateStu_id($attribute,$params)
    {
        if(Score::find()->where(['stu_id'=>$this->stu_id])->andWhere(['type'=>$this->type])->one()){
            $this->addError($attribute, '学生该科成绩已上传，请点击修改');
        }else{
            $student=Student::findOne(['id'=>$this->stu_id]);
            if($student){
                if($student->tag==0){
                    $this->addError($attribute, '该学生已经删除');
                }
            }else{
                $this->addError($attribute, '学生id不存在');
            }
        }
    }

    /*
     * 修改成绩时的验证
     */
    public function validateStu_idAlive($attribute,$params)
    {
        $student=Student::findOne(['id'=>$this->stu_id]);
        if($student->tag==0){
            $this->addError($attribute, '该学生已删除，不能再修改成绩');
        }
    }
    public function scenarios()
    {
        return [
            'add' => ['score', 'stu_id','type'],
            'modify' => ['score', 'stu_id'],
        ];
    }

    public static function tableName()
    {
        return 'score';
    }

    /**
     * @param $id
     * @return static[]
     * 根据学生id查询所有分类成绩
     */
    public static function getScoresById($id){
        return Score::findAll(['stu_id'=>$id]);
    }

    /**
     *获取所有学生成绩
     */
    public static function getAllScores()
    {
        return Score::find();
    }
}